package com.tim.arc.groovy;

import cn.hutool.crypto.digest.MD5;
import groovy.lang.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class ClassExecute{

    public static void main(String[] args) throws Exception {
//        executeClassDefine();
        executeHelloWorldJava();
    }

    public static void executeClassDefine() throws Exception {
        String path="D:\\project\\autil\\autil\\src\\main\\java\\com\\tim\\arc\\groovy\\base\\ClassDefine.groovy" +
                "";
        String name="hello";
        Object args=null;
        execute(path, name, args);

    }

    public static void executeHelloWorldJava() throws Exception {
        String path="D:\\project\\autil\\autil\\src\\main\\java\\com\\tim\\arc\\groovy\\HelloWorldJava.java" +
                "";
        String name="main";
        Object args=null;
        execute(path, name, args);

    }

    static Map<String, Class> map=new HashMap<>();
    public static void execute(String path, String name, Object args) throws IOException, InstantiationException, IllegalAccessException {
        String content = Files.readAllLines(Paths.get(path)).stream().collect(Collectors.joining("\n"));
        String md5 = MD5.create().digestHex(content);
        Class aClass = map.get(md5);
        if(aClass==null){
            GroovyClassLoader classLoader=new GroovyClassLoader();
            aClass = classLoader.parseClass(content);//编译字节码，获取class
            map.put(md5, aClass);
        }
        GroovyObject groovyObject = (GroovyObject) aClass.newInstance();
        Object result = groovyObject.invokeMethod(name, args);
        System.out.println("execute result: "+result);

    }
}
